<?php

namespace app\apiz\controller\product;

use think\Controller;
use think\Cookie;

class Order extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->TypeModel = model('Product.Type');
        $this->ProductModel = model('Product.Product');
        $this->UserModel = model('User.User');
        $this->CartModel = model('Cart');
        $this->RecordModel = model('User.Record');
        $this->AddressModel = model('User.Address');
        $this->OrderModel = model('Order.Order');
        $this->OrderProductModel = model('Order.Product');
        $this->StoreModel = model('Order.Store');
        $this->RefundModel = model('Order.Refund');


    }
    public function orderadd()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $proid = $this->request->param('proid', 0);
            $nums = $this->request->param('nums', 0);
            $price = $this->request->param('price', '');

            $User = $this->UserModel->find($userid);

            if(!$User)
            {
                $this->error('用户不存在');
                exit;
            }

            $product = $this->ProductModel->find($proid);

            if(!$product)
            {
                $this->error('商品不存在');
                exit;
            }
            $total = $price * $nums;
            $data = [
                'total' => $total,
                'userid' => $userid,
                'proid' => $proid,
                'price' => $price
            ];

            $this->success('返回商品数据成功', null, $data);
            exit;
        } 
    }
    // 默认收货地址
    public function addrorder()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);

            $user = $this->UserModel->find($userid);

            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'userid' => $userid,
                'status' => 1
            ];

            //查找这个人的默认收货地址
            $address = $this->AddressModel->with(['provinces', 'citys', 'districts'])->where($where)->find();

            if($address)
            {
                $this->success('返回默认收货地址', null, $address);
                exit;
            }

            //如果没有默认的收货地址，就随便找一条给他
            $info = $this->AddressModel->with(['provinces', 'citys', 'districts'])->where(['userid' => $userid])->find();

            if(!$info)
            {
                $this->error('暂无收货地址');
                exit;
            }

            $this->success('返回默认收货地址', null, $info);
            exit;

            
        }
    }

    public function cartinfo()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $proid = $this->request->param('proid', 0);

            $user = $this->UserModel->find($userid);

            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }

            $product = $this->ProductModel->find($proid);

            if(!$product)
            {
                $this->error('商品不存在');
                exit;
            }

            $where = [
                'userid'=>$userid,
                'proid'=>$proid
            ];

            $result = $this->CartModel->where($where)->select();

            if($result == FALSE)
            {
                $this->error('返回购物车信息失败');
                exit;
            }else
            {
                $this->success('返回购物车信息成功', null, $result);
                exit;
            }
        }
    }

    public function toorder()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $addrid = $this->request->param('addrid', 0);
            $cartids = $this->request->param('cartids', 0);
            $content = $this->request->param('content', '');

            $user = $this->UserModel->find($userid);

            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'id' => $addrid,
                'userid' => $userid
            ];

            //判断收货地址是否存在
            $address = $this->AddressModel->where($where)->find();

            if(!$address)
            {
                $this->error('收货地址不存在，请重新选择');
                exit;
            }
            
            $where = [
                'cart.id' => ['in', $cartids],
                'userid' => $userid
            ];

            $cartlist = $this->CartModel->with(['product'])->where($where)->select();
            
            if(!$cartlist)
            {
                $this->error('下单数据为空，请重新选择商品');
                exit;
            }
            
            //判断商品库存是否充足
            foreach($cartlist as $item)
            {
                //购物车的数量 和商品的库存
                $nums = $item['nums'];
                $stock = $item['product']['stock'];

                //让库存 - 购物车数量
                $pronums = bcsub($stock, $nums);

                if($pronums < 0)
                {
                    $this->error($item['product']['name']."库存不足，请重新选择");
                    exit;
                }
            }

            //查询下单数据的总价格
            $where = [
                'id' => ['in', $cartids],
                'userid' => $userid
            ];
            
            $total = $this->CartModel->where($where)->sum('total');

            $point = $user['point'];

            //让用户积分 -  总价
            $UpdatePoint = bcsub($point, $total);

            if($UpdatePoint < 0)
            {
                $this->error('积分不足，请充值后操作');
                exit;
            }

             //订单表(INSERT) 订单商品表(INSERT) 商品库存(update) 
             //用户积分(update) 消费记录(insert) 购物车(delete)
            //开启事务
            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CartModel->startTrans();


            //组装订单表数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code("SF"),
                'content' => $content,
                'status' => 1,
                'total' => $total
            ];
            //订单表
            $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

            if($OrderStatus === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }

            //组装订单商品的数据
            $OrderProductData = [];
            $ProductData = [];

            foreach($cartlist as $item)
            {
                $OrderProductData[] = [
                    'orderid' => $this->OrderModel->id,
                    'proid' => $item['proid'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total'],
                ];

                //商品库存 - 购物车数量
                $stock = bcsub($item['product']['stock'], $item['nums']);

                $ProductData[] = [
                    'id' => $item['proid'],
                    'stock' => $stock,
                ];
            }

            $OrderProductStatus = $this->OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

            if($OrderProductStatus == FALSE)
            {
                $this->OrderModel->rollback();
                $this->error($this->OrderProductModel->getError());
                exit;
            }

             //商品更新库存
            $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);
            if($ProductStatus == FALSE)
            {
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->ProductModel->geterror());
                exit;
            }

            //更新用户积分
            $UserData = [
                'id' => $userid,
                'point' => $UpdatePoint
            ];

            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if($UserStatus == FALSE)
            {
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 消费记录
            $RecordData = [
                'point' => $total,
                'content' => "订单号：".$OrderData['code']."---消费的积分为：$total",
                'state' => 5,
                'userid' => $userid
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
            if($RecordStatus == FALSE)
            {
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            // 购物车(delete)
            $CartStatus = $this->CartModel->destroy($cartids);

            if($CartStatus === FALSE)
            {
                //回滚
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->CartModel->getError());
                exit;
            }

            if($OrderStatus !== FALSE && $OrderProductStatus !== FALSE && $ProductStatus !== FALSE && $UserStatus !== FALSE && $RecordStatus !== FALSE && $CartStatus !== FALSE)
            {
                //提交事务
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->ProductModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->CartModel->commit();

                $this->success('下单成功，等待商家发货');
                exit;
            }else
            {
                $this->CartModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error('下单失败,请重新操作');
                exit;
            }


        }
    }

    public function toorder1()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $addrid = $this->request->param('addrid', 0);
            $content = $this->request->param('content', '');
            $user = $this->UserModel->find($userid);
            $num = $this->request->param('num',0);
            $proid = $this->request->param('proid',0);
            $total = $this->request->param('total',0);
            $price = $this->request->param('price',0);



            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'id' => $addrid,
                'userid' => $userid
            ];

            //判断收货地址是否存在
            $address = $this->AddressModel->where($where)->find();

            if(!$address)
            {
                $this->error('收货地址不存在，请重新选择');
                exit;
            }

            $product = $this->ProductModel->find($proid);

            if(!$product)
            {
                $this->error('商品不存在');
                exit;
            }
            //判断商品库存是否充足
            //购物车的数量 和商品的库存
            $stock = $product['stock'];
            //让库存 - 购物车数量
            $pronums = bcsub($stock, $num);

            if($pronums < 0)
            {
                $this->error($product['name']."库存不足，请重新选择");
                exit;
            }

            $point = $user['point'];

            //让用户积分 -  总价
            $UpdatePoint = bcsub($point, $total);

            if($UpdatePoint < 0)
            {
                $this->error('积分不足，请充值后操作');
                exit;
            }

             //订单表(INSERT) 订单商品表(INSERT) 商品库存(update) 
             //用户积分(update) 消费记录(insert) 购物车(delete)
            //开启事务
            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();


            //组装订单表数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code("SF"),
                'content' => $content,
                'status' => 1,
                'total' => $total
            ];
            //订单表
            $OrderStatus = $this->OrderModel->validate('common/Order/Order')->save($OrderData);

            if($OrderStatus === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }




            //组装订单商品的数据
            $OrderProductData = [];
            $ProductData = [];

            $OrderProductData[] = [
                'orderid' => $this->OrderModel->id,
                'proid' => $proid,
                'nums' => $num,
                'price' => $price,
                'total' => $total,
            ];

            //商品库存 - 购物车数量
            $stock = bcsub($product['stock'], $num);

            $ProductData[] = [
                'id' => $proid,
                'stock' => $stock,
            ];
            

            $OrderProductStatus = $this->OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

            if($OrderProductStatus == FALSE)
            {
                $this->OrderModel->rollback();
                $this->error($this->OrderProductModel->getError());
                exit;
            }

             //商品更新库存
            $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);
            if($ProductStatus == FALSE)
            {
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->ProductModel->geterror());
                exit;
            }

            //更新用户积分
            $UserData = [
                'id' => $userid,
                'point' => $UpdatePoint
            ];

            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if($UserStatus == FALSE)
            {
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 消费记录
            $RecordData = [
                'point' => $total,
                'content' => "订单号：".$OrderData['code']."---消费的积分为：$total",
                'state' => 5,
                'userid' => $userid
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
            if($RecordStatus == FALSE)
            {
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if($OrderStatus !== FALSE && $OrderProductStatus !== FALSE && $ProductStatus !== FALSE && $UserStatus !== FALSE && $RecordStatus !== FALSE)
            {
                //提交事务
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->ProductModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();

                $this->success('下单成功，等待商家发货');
                exit;
            }else
            {
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error('下单失败,请重新操作');
                exit;
            } 
        }
    }

    public function orderdata()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $status = $this->request->param('status', 0);
            $user = $this->UserModel->find($userid);
            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'userid' => $userid
            ];

            if($status != 0)
            {
                $where['status'] = $status;
            }

            $order = $this->OrderModel->where($where)->select();

            if(!$order)
            {
                $this->success('暂无订单数据');
                exit;
            }
            $orderlist = [];

            foreach($order as $item)
            {
                $info = [
                    'id' => $item['id'],
                    'code' => $item['code'],
                    'total' => $item['total'],
                    'createtime' => $item['createtime'],
                    'status' => $item['status'],
                    'status_text' => $item['status_text'],
                ];

                $product = $this->OrderProductModel->with(['info'])->where(['orderid'=> $item['id']])->find();
                
                if($product && $product['info']['id'])
                {
                    $info['product'] = $product['info'];
                }

                $orderlist[] = $info;
            }

            $this->success('返回订单数据', null, $orderlist);
            exit;
        }
    }

    public function info()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $orderid = $this->request->param('orderid', 0);
            $user = $this->UserModel->find($userid);
            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }
            $where = [
                'userid' => $userid,
                'id' => $orderid
            ];

            $order = $this->OrderModel->where($where)->find();

            if(!$order)
            {
                $this->error('订单不存在');
                exit;
            }

            //订单商品
            $product = $this->OrderProductModel->with(['info'])->where(['orderid' => $orderid])->select();

            //判断订单商品是否存在
            if(!$product)
            {
                $this->error('订单商品不存在');
                exit;
            }

            //获取订单的收货地址
            $address = $this->AddressModel->with(['provinces', 'citys', 'districts'])->find($order['addrid']);

            if(!$address)
            {
                $this->error('未找到订单的收货地址');
                exit;
            }

            $data = [
                'order' => $order,
                'product' => $product,
                'address' => $address
            ];

            $this->success('返回订单数据成功', null, $data);
            exit;
        }
    }

    public function storeadd()
    {
        if($this->request->isPost())
        {
            $params = $this->request->param();
            $userid = $this->request->param('userid', 0);
            $orderid = $this->request->param('orderid', 0);

            $user = $this->UserModel->find($userid);

            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }
            $order = $this->OrderModel->find($orderid);

            if(!$order)
            {
                $this->error('订单不存在');
                exit;
            }
            
            $data = [
                'userid' => $userid,
                'orderid' => $orderid,
                'store' => $params['store'],
                'content' => $params['review'],
            ];
            if(isset($_FILES['images']) && $_FILES['images']['size'] > 0)
            {
                
                $result = upload('images');
                
                if($result === FALSE)
                {
                    $this->error('上传图片失败');
                    exit;
                }
                
                $data['thumbs'] = 'uploads/'.$result;
            }
            $store = $this->StoreModel->find($orderid);
            if($store)
            {
                $this->error('您已对该订单进行了评价，无需重复评价');
                exit;
            }
            $result = $this->StoreModel->save($data);

            if($result ==FALSE)
            {
                $this->error("评价失败");
                exit;
            }
            $data = [
                'id' => $orderid,
                'status' => 4
            ];
            $status = $this->OrderModel->isUpdate(true)->save($data);

            if($status == FALSE)
            {
                $this->error("评价失败");
                exit;
            }
            $this->success('评价成功,感谢您对我们的支持！');
            exit;
            
        }
    }

    public function storedata()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0);
            $orderid = $this->request->param('orderid', 0);

            $user = $this->UserModel->find($userid);

            if(!$user)
            {
                $this->error('用户不存在');
                exit;
            }
            $order = $this->OrderModel->find($orderid);

            if(!$order)
            {
                $this->error('订单不存在');
                exit;
            }
            $where = [
                'userid' => $userid,
                'orderid' => $orderid
            ];

            $store = $this->StoreModel->where($where)->select();
            
            if(!$store)
            {
                $data = [
                    'store' => 0,
                    'content' => ''
                ];
                $this->error('用户未评价',null,$data);
                exit;
            }else
            {
                $this->success('返回评价数据成功',null, $store);
                exit;
            }


        }
    }

    // 申请退货
    public function refund()
    {
        if($this->request->isPost())
        {
            $userid=$this->request->param('userid',0);
            $orderid=$this->request->param("orderid",0);
            $proid=$this->request->param('proid',0);
            $content=$this->request->param('content','');
        
            // 组装条件
            $where=[
                'userid'=>$userid,
                'id'=>$orderid
            ];
    
            // 查询订单是否存在
            $order=$this->OrderModel->where($where)->find();
    
            if(!$order)
            {
                $this->error('订单不存在');
                exit;
            }
    
            // 订单商品
            $product=$this->OrderProductModel->with(['info'])->where(['orderid'=>$orderid])->select();
            
    
            if(!$product)
            {
                $this->error('订单商品不存在');
                exit;
            }
    
            $OrderReData = [
                'orderid' => $orderid,
                'userid' => $userid,
                'content' => $content,
                'status' => 0
            ];

            if(isset($_FILES['reImg']) && $_FILES['reImg']['size'] > 0)
            {
                // 本地文件上传
                $result=upload('reImg');

                if($result === FALSE)
                {
                    $this->error('上传图片失败');
                    exit;
                }

                // 追加图片
                $OrderReData['thumbs']='uploads/'.$result;

                }

                // 开启事务
                $this->RefundModel->startTrans();
                $this->ProductModel->startTrans();
                $this->UserModel->startTrans();
                $this->OrderModel->startTrans();
              

                // 退货表
                $OrderReResult=$this->RefundModel->validate('common/Order/Refund')->save($OrderReData);

                if(!$OrderReResult)
                {
                    $this->error($this->RefundModel->getError());
                    exit;
                }

                // 查看当前的订单商品总价
                $where=[
                    'orderid'=>$orderid,
                    'proid'=>$proid
                ];

                $proNums = $this->OrderProductModel->where($where)->value('nums');

                $proTotal = $this->OrderProductModel->where($where)->value('total');

                if(!$proTotal || !$proNums){
                    $this->error('未找到商品的总价或商品数量');
                    exit;
                }

              
                // 商品表
                $ProductResult = $this->ProductModel->where(['id' => $proid])->setInc('stock',$proNums);

                if(!$ProductResult){
                    $this->RefundModel->rollback();

                    $this->error($this->ProductModel->getError());
                    exit;
                }

                // 用户表
                $UserResult = $this->UserModel->where(['id' => $userid])->setInc('point',$proTotal);

                if(!$UserResult){
                    $this->ProductModel->rollback();
                    $this->RefundModel->rollback();

                    $this->error($this->UserModel->getError());
                    exit;
                }

                $OrderData = [
                    'id' => $orderid,
                    'status' => -1
                ];
                
                $OrderResult = $this->OrderModel->isUpdate('true')->save($OrderData);

                if(!$OrderResult){
                    $this->RefundModel->rollback();

                    $this->error($this->OrderModel->getError());
                    exit;
                }


                if(!$OrderReResult || !$ProductResult || !$UserResult || !$OrderResult){
                    $this->OrderModel->rollback();
                    $this->UesrModel->rollback();
                    $this->ProductModel->rollback();
                    $this->RefundModel->rollback();
                   
                
                    $this->error('申请退货失败');
                    exit;
                }

                else{
                   
                    $this->RefundModel->commit();
                    $this->ProductModel->commit();
                    $this->UserModel->commit();
                    $this->OrderModel->commit();

                    $this->success('申请退货成功，请等待审核');
                    exit;
                }
            }
    }

    public function prodata()
    {
        $userid=$this->request->param('userid',0);
        $proid=$this->request->param('proid',0);
        $user = $this->UserModel->find($userid);

        if(!$user)
        {
            $this->error('用户不存在');
            exit;
        }

        $product = $this->ProductModel->find($proid);

        if(!$product)
        {
            $this->error('商品不存在');
            exit;
        }else
        {
            $this->success('返回商品数据',null,$product);
            exit;
        }


    }


  
}